package com.faithbj.controller.infoInput;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.faithbj.common.configuration.Pager;
import com.faithbj.common.model.CheckTotal;
import com.faithbj.common.model.EntrustInfo;
import com.faithbj.common.model.fm.FamilyMember;
import com.faithbj.common.model.fm.FamilyMemberIncome;
import com.faithbj.common.web.controller.BaseController;
import com.faithbj.service.CheckTotalService;
import com.faithbj.service.FamilyMemberService;

@Controller
@RequestMapping("/infoInput")
public class InfoInputController extends BaseController {

	private static final long serialVersionUID = 9068281894134828427L;

	private final Logger logger = LoggerFactory
			.getLogger(InfoInputController.class);

	@Resource
	private CheckTotalService checkTotalService;

	@Resource
	private FamilyMemberService familyMemberService;

	private static SimpleDateFormat dateFormat = new SimpleDateFormat(
			"yyyy-MM-dd");

	@InitBinder
	@Override
	public void initBinder(WebDataBinder binder) {
		dateFormat.setLenient(false);
		binder.registerCustomEditor(Date.class, new CustomDateEditor(
				dateFormat, false));
	}

	@RequestMapping(value = "/index")
	public String list(HttpServletRequest request, ModelMap map) {
		Pager pager = new Pager();
		int pageNumber = 0;
		try {
			pageNumber = Integer.valueOf(request.getParameter("pageNumber"));
		} catch (Exception e) {
			pageNumber = 0;
		}
		pager.setPageNumber(pageNumber);
		pager = checkTotalService.getCheckTotalListForApplyInfo(pager);
		map.put("pager", pager);
		return "/infoInput/index";
	}

	@RequestMapping(value = "/searchPage")
	public String getSearchPage() {
		return "/infoInput/search";
	}

	@RequestMapping(value = "/familyBasicInfo/{id}")
	public String getCheckTotalById(@PathVariable String id, ModelMap map) {
		CheckTotal checkTotal = checkTotalService.getCheckTotalById(id);
		Set<FamilyMember> members = checkTotal.getFamilyMembers();
		for (FamilyMember fm : members) {
			if (fm.getMainApplicant()) {
				map.put("fm", fm);
			}
		}
		map.put("checkTotal", checkTotal);
		return "/infoInput/familyBasic";
	}

	@ResponseBody
	@RequestMapping(value = "/updateFamilyBasicInfo", method = RequestMethod.POST)
	public Map updateCheckTotal(HttpServletRequest request) {
		Map map = new HashMap();
		try {
			// 核对总体情况
			String checkTotalId = request.getParameter("checkTotalId");
			CheckTotal ct = checkTotalService.getCheckTotalById(checkTotalId);

			// 委托信息
			EntrustInfo et = ct.getEntrustInfo();
			if (et == null) {
				et = new EntrustInfo();
			}
			et.setCtId(ct.getId());
			et.setType(request.getParameter("entrustType"));
			et.setEntrustOrg(request.getParameter("entrustOrg"));
			et.setIdType(request.getParameter("entrustIdType"));
			et.setIdNumber(request.getParameter("entrustIdNumber"));
			et.setEntrustPerson(request.getParameter("entrustPerson"));
			et.setEntrustNumber(request.getParameter("entrustNumber"));
			String entrustDateString = request.getParameter("entrustDate");
			et.setEntrustDate(dateFormat.parse(entrustDateString));
			et.setPhone(request.getParameter("entrustPhone"));
			et.setHouseholdLevel1(request
					.getParameter("entrustHouseholdLevel1"));
			et.setHouseholdLevel2(request
					.getParameter("entrustHouseholdLevel2"));
			et.setHouseholdLevel3(request
					.getParameter("entrustHouseholdLevel3"));
			et.setHouseholdLevel4(request
					.getParameter("entrustHouseholdLevel4"));
			et.setHouseholdLevel5(request
					.getParameter("entrustHouseholdLevel5"));
			et.setLivingLevel1(request.getParameter("entrustLivingLevel1"));
			et.setLivingLevel2(request.getParameter("entrustLivingLevel2"));
			et.setLivingLevel3(request.getParameter("entrustLivingLevel3"));
			et.setLivingLevel4(request.getParameter("entrustLivingLevel4"));
			et.setLivingLevel5(request.getParameter("entrustLivingLevel5"));
			ct.setEntrustInfo(et);

			// 主家庭成员
			FamilyMember fm = ct.getFamilyMember();
			fm.setIdType(request.getParameter("familyMemberIdType"));
			fm.setIdNumber(request.getParameter("familyMemberIdNumber"));
			fm.setName(request.getParameter("familyMemberName"));

			checkTotalService.updateCheckTotal(ct);

			map.put("result", true);
		} catch (Exception e) {
			map.put("result", false);
		}
		return map;
	}

	@RequestMapping(value = "/familyMemberInfo/{id}")
	public String getFamilyMembers(@PathVariable String id, ModelMap map) {
		List<FamilyMember> familyMembers = familyMemberService
				.getFamilyMembersByCheckTotal(id);
		map.put("familyMembers", familyMembers);
		map.put("checkTotalId", id);
		return "/infoInput/familyMember";
	}

	@RequestMapping(value = "/addFamilyMemberInfo")
	public String addFamilyMember(HttpServletRequest request) {
		try {
			// 核对总体情况
			String checkTotalId = request.getParameter("checkTotalId");
			CheckTotal ct = checkTotalService.getCheckTotalById(checkTotalId);

			if (ct != null) {
				FamilyMember fm = new FamilyMember();
				fm.setCheckTotal(ct);
				fm.setIdType(request.getParameter("idType"));
				fm.setIdNumber(request.getParameter("idNumber"));
				fm.setName(request.getParameter("name"));
				fm.setGender(request.getParameter("gender"));
				fm.setMaritalStatus(request.getParameter("maritalStatus"));
				fm.setEducation(request.getParameter("education"));
				String birthdayString = request.getParameter("birthday");
				fm.setBirthday(dateFormat.parse(birthdayString));

				fm.setNation(request.getParameter("nation"));
				fm.setCountry(request.getParameter("country"));
				fm.setPoliticalStatus(request.getParameter("politicalStatus"));
				fm.setHouseholdType(request.getParameter("householdType"));
				fm.setHouseholdAddress(request.getParameter("householdAddress"));
				fm.setHouseholdDistrictCode(request
						.getParameter("householdDistrictCode"));
				fm.setLivingAddress(request.getParameter("livingAddress"));
				fm.setLivingDistrictCode(request
						.getParameter("livingDistrictCode"));
				String startDateLivingString = request
						.getParameter("startDateLiving");
				fm.setStartDateLiving(dateFormat.parse(startDateLivingString));
				fm.setHealthStatus(request.getParameter("healthStatus"));
				fm.setLaborLossStatus(request.getParameter("laborLossStatus"));
				fm.setDisabilityDegree(request.getParameter("disabilityDegree"));
				fm.setDiseaseName(request.getParameter("diseaseName"));
				boolean mainApplicant = request
						.getParameter("householdAddress").equals("true") ? true
						: false;
				fm.setMainApplicant(mainApplicant);
				fm.setRelationMainApplicant(request
						.getParameter("relationMainApplicant"));
				fm.setPhone(request.getParameter("phone"));
				fm.setMobile(request.getParameter("mobile"));
				fm.setZipCode(request.getParameter("zipCode"));
				fm.setContactAddress(request.getParameter("contactAddress"));
				familyMemberService.addFamilyMember(fm);
			} else {
				// TODO 跳转到错误页面
				logger.error("添加家庭成员出错");
			}
		} catch (Exception e) {
			// TODO 跳转到错误页面
			logger.error("添加家庭成员出错", e);
		}

		return "/infoInput/familyMember";
	}

	@ResponseBody
	@RequestMapping(value = "/deleteFamilyMemberInfo/{id}")
	public Map deleteFamilyMemberInfo(@PathVariable String id) {
		Map map = new HashMap();
		try {
			FamilyMember fm = familyMemberService.getFamilyMemberById(id);
			if (fm != null) {
				familyMemberService.deleteFamilyMemberInfo(id);
			}
			map.put("result", true);
		} catch (Exception e) {
			logger.error("删除家庭成员出错", e);
			map.put("result", false);
		}
		return map;
	}

	@ResponseBody
	@RequestMapping(value = "/updateFamilyMemberInfo", method = RequestMethod.POST)
	public Map updateFamilyMember(HttpServletRequest request) {
		Map map = new HashMap();
		FamilyMember fm = null;
		try {

			String checkTotalId = request.getParameter("checkTotalId");
			CheckTotal ct = checkTotalService.getCheckTotalById(checkTotalId);

			String familyMemberId = request.getParameter("familyMemberId");
			if (familyMemberId == null || familyMemberId.equals("")) {
				fm = new FamilyMember();
				fm.setCheckTotal(ct);
			} else {
				fm = familyMemberService.getFamilyMemberById(familyMemberId);
			}
			fm.setIdType(request.getParameter("idType"));
			fm.setIdNumber(request.getParameter("idNumber"));
			fm.setName(request.getParameter("name"));
			fm.setGender(request.getParameter("gender"));
			fm.setMaritalStatus(request.getParameter("maritalStatus"));
			fm.setEducation(request.getParameter("education"));
			String birthdayString = request.getParameter("birthday");
			fm.setBirthday(dateFormat.parse(birthdayString));

			// fm.setNation(request.getParameter("nation"));
			// fm.setCountry(request.getParameter("country"));
			// fm.setPoliticalStatus(request.getParameter("politicalStatus"));
			// fm.setHouseholdType(request.getParameter("householdType"));
			// fm.setHouseholdAddress(request.getParameter("householdAddress"));
			// fm.setHouseholdDistrictCode(request
			// .getParameter("householdDistrictCode"));
			// fm.setLivingAddress(request.getParameter("livingAddress"));
			// fm.setLivingDistrictCode(request.getParameter("livingDistrictCode"));
			// String startDateLivingString = request
			// .getParameter("startDateLiving");
			// fm.setStartDateLiving(dateFormat.parse(startDateLivingString));
			// fm.setHealthStatus(request.getParameter("healthStatus"));
			// fm.setLaborLossStatus(request.getParameter("laborLossStatus"));
			// fm.setDisabilityDegree(request.getParameter("disabilityDegree"));
			// fm.setDiseaseName(request.getParameter("diseaseName"));
			// boolean mainApplicant = request.getParameter("householdAddress")
			// .equals("true") ? true : false;
			// fm.setMainApplicant(mainApplicant);
			// fm.setRelationMainApplicant(request
			// .getParameter("relationMainApplicant"));
			// fm.setPhone(request.getParameter("phone"));
			// fm.setMobile(request.getParameter("mobile"));
			// fm.setZipCode(request.getParameter("zipCode"));
			// fm.setContactAddress(request.getParameter("contactAddress"));

			familyMemberService.updateFamilyMember(fm);
			map.put("result", true);
		} catch (Exception e) {
			logger.error("更新家庭成员出错", e);
			map.put("result", false);
		}
		return map;
	}

	@RequestMapping(value = "/familyMemberIncome/{id}")
	public String getFamilyMemberIncomes(@PathVariable String id, ModelMap map) {
		List<FamilyMember> familyMembers = familyMemberService
				.getFamilyMembersByCheckTotal(id);
		map.put("familyMembers", familyMembers);
		map.put("checkTotalId", id);
		return "/infoInput/memberIncome";
	}

	@ResponseBody
	@RequestMapping(value = "/updateFamilyMemberIncome", method = RequestMethod.POST)
	public Map updateFamilyMemberIncome(HttpServletRequest request) {
		Map map = new HashMap();

		try {
			String familyMemberId = request.getParameter("familyMemberId");
			FamilyMember fm = familyMemberService
					.getFamilyMemberById(familyMemberId);

			if (fm != null) {

				FamilyMemberIncome fmi = fm.getIncome();

				if (fmi == null) {
					fmi = new FamilyMemberIncome();
					fm.setIncome(fmi);
				}

				// 工资性收入
				String salaryIncome = request.getParameter("salaryIncome");
				fmi.setSalaryIncome(new BigDecimal(salaryIncome));
				String bonusIncome = request.getParameter("bonusIncome");
				fmi.setBonusIncome(new BigDecimal(bonusIncome));
				String subsidyIncome = request.getParameter("subsidyIncome");
				fmi.setSubsidyIncome(new BigDecimal(subsidyIncome));
				String overtimeIncome = request.getParameter("overtimeIncome");
				fmi.setOvertimeIncome(new BigDecimal(overtimeIncome));
				String secondEmployIncome = request
						.getParameter("secondEmployIncome");
				fmi.setSecondEmployIncome(new BigDecimal(secondEmployIncome));
				String partTimeIncome = request.getParameter("partTimeIncome");
				fmi.setPartTimeIncome(new BigDecimal(partTimeIncome));
				String otherIncome = request.getParameter("otherIncome");
				fmi.setOtherIncome(new BigDecimal(otherIncome));
				String agriculteIncome = request
						.getParameter("agriculteIncome");
				fmi.setAgriculteIncome(new BigDecimal(agriculteIncome));
				String distributeIncome = request
						.getParameter("distributeIncome");
				fmi.setDistributeIncome(new BigDecimal(distributeIncome));

				// 经营性收入
				String registerIncome = request.getParameter("registerIncome");
				fmi.setRegisterIncome(new BigDecimal(registerIncome));
				String unRegisterIncome = request
						.getParameter("unRegisterIncome");
				fmi.setUnRegisterIncome(new BigDecimal(unRegisterIncome));

				// 财产性收入
				String bankInterestIncome = request
						.getParameter("bankInterestIncome");
				fmi.setBankInterestIncome(new BigDecimal(bankInterestIncome));
				String fundIncome = request.getParameter("fundIncome");
				fmi.setFundIncome(new BigDecimal(fundIncome));
				String stockIncome = request.getParameter("stockIncome");
				fmi.setStockIncome(new BigDecimal(stockIncome));
				String insuranceIncome = request
						.getParameter("insuranceIncome");
				fmi.setInsuranceIncome(new BigDecimal(insuranceIncome));
				String rentalHouseIncome = request
						.getParameter("rentalHouseIncome");
				fmi.setRentalHouseIncome(new BigDecimal(rentalHouseIncome));
				String knowledgeIncome = request
						.getParameter("knowledgeIncome");
				fmi.setKnowledgeIncome(new BigDecimal(knowledgeIncome));
				String otherInvestIncome = request
						.getParameter("otherInvestIncome");
				fmi.setOtherInvestIncome(new BigDecimal(otherInvestIncome));
				String otherPropertyIncome = request
						.getParameter("otherPropertyIncome");
				fmi.setOtherPropertyIncome(new BigDecimal(otherPropertyIncome));

				// 转移性收入
				String unemployInsurance = request
						.getParameter("unemployInsurance");
				fmi.setUnemployInsurance(new BigDecimal(unemployInsurance));
				String pension = request.getParameter("pension");
				fmi.setPension(new BigDecimal(pension));
				String retired = request.getParameter("retired");
				fmi.setRetired(new BigDecimal(retired));
				String assistantIncome = request
						.getParameter("assistantIncome");
				fmi.setAssistantIncome(new BigDecimal(assistantIncome));
				String jobsSubsidy = request.getParameter("jobsSubsidy");
				fmi.setJobsSubsidy(new BigDecimal(jobsSubsidy));
				String socialInsuranceSubsidy = request
						.getParameter("socialInsuranceSubsidy");
				fmi.setSocialInsuranceSubsidy(new BigDecimal(
						socialInsuranceSubsidy));
				String survivorsSubsidy = request
						.getParameter("survivorsSubsidy");
				fmi.setSurvivorsSubsidy(new BigDecimal(survivorsSubsidy));
				String lotteryIncome = request.getParameter("lotteryIncome");
				fmi.setLotteryIncome(new BigDecimal(lotteryIncome));
				String alimony = request.getParameter("alimony");
				fmi.setAlimony(new BigDecimal(alimony));
				String dismiss = request.getParameter("dismiss");
				fmi.setDismiss(new BigDecimal(dismiss));
				String compensationIncome = request
						.getParameter("compensationIncome");
				fmi.setCompensationIncome(new BigDecimal(compensationIncome));
				String donation = request.getParameter("donation");
				fmi.setDonation(new BigDecimal(donation));
				String giftIncome = request.getParameter("giftIncome");
				fmi.setGiftIncome(new BigDecimal(giftIncome));
				String inheritanceIncome = request
						.getParameter("inheritanceIncome");
				fmi.setInheritanceIncome(new BigDecimal(inheritanceIncome));
				String scholarship = request.getParameter("scholarship");
				fmi.setScholarship(new BigDecimal(scholarship));
				String soldierSubsidy = request.getParameter("soldierSubsidy");
				fmi.setSoldierSubsidy(new BigDecimal(soldierSubsidy));
				String highSubsidy = request.getParameter("highSubsidy");
				fmi.setHighSubsidy(new BigDecimal(highSubsidy));
				String heatingSubsidy = request.getParameter("heatingSubsidy");
				fmi.setHeatingSubsidy(new BigDecimal(heatingSubsidy));
				String friendsPartnerFee = request
						.getParameter("friendsPartnerFee");
				fmi.setFriendsPartnerFee(new BigDecimal(friendsPartnerFee));
				String oneTimeAddPension = request
						.getParameter("oneTimeAddPension");
				fmi.setOneTimeAddPension(new BigDecimal(oneTimeAddPension));
				String oneTimeHouseFund = request
						.getParameter("oneTimeHouseFund");
				fmi.setOneTimeHouseFund(new BigDecimal(oneTimeHouseFund));
				String oneTimeAddHouseFund = request
						.getParameter("oneTimeAddHouseFund");
				fmi.setOneTimeAddHouseFund(new BigDecimal(oneTimeAddHouseFund));
				String otherSubsidy = request.getParameter("otherSubsidy");
				fmi.setOtherSubsidy(new BigDecimal(otherSubsidy));

				familyMemberService.updateFamilyMember(fm);
				map.put("result", true);
			} else {
				// TODO 跳转错误页面
				logger.error("更新家庭成员收入出错");
			}
		} catch (Exception e) {
			logger.error("更新家庭成员收入出错", e);
			map.put("result", false);
		}
		return map;
	}

}
